// axios配置
import axios from "axios";
// 引入ElementUI中的全局提示方法
// import ElementUI from "element-ui";
import { Message, MessageBox, Loading } from "element-ui";
import storage from "./storage";

let http = axios.create({
  withCredentials: true, //是否携带凭证
  baseURL: "/api", //基础地址
  timeout: 5000, //超时设置
  // requestInterceptor: (config) => {
  //   const token = storage.get("token");
  //   if (token) {
  //     config.headers.Authorization = `Bearer ${token}`;
  //   }
  // },
});
let fullScreenLoading = null;
// 请求拦截
http.interceptors.request.use((config) => {
  //先获取本地的token,然后携带给后端
  let token = storage.get("token");
  // console.log(token)
  config.headers["authorization"] = token;
  // config.params.category_id = "20210827165510715";
  // config就是所有的请求配置

  //登入的时候打开加载动画
  console.log(config);

  //关键字 login wechatLogin

  if (
    config.url.indexOf("login") !== -1 ||
    config.url.indexOf("wechatLogin") !== -1
  ) {
    fullScreenLoading = Loading.service({
      lock: true,
      text: "加载中...",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
  }

  // let token = storage.get("token");
  // if (token) {
  //   config.headers.authorization = token;
  // }
  // config就是请求的对象，里面可以拿到请求的地址、参数等
  return config; //可以理解为放行
});

// 响应拦截
http.interceptors.response.use((config) => {
  if (fullScreenLoading) {
    fullScreenLoading.close();
    fullScreenLoading = null;
  }
  // config就是响应的对象，里面可以拿到服务器响应的内容
  //嵌套解构语法
  let { state, msg } = config.data;
  if (!state) {
    //后台响应了错误的结果
    MessageBox({
      message: msg,
      title: "错误提示",
      type: "error",
    });
  }

  let { code } = config.data;

  if (code === "10022" || code === "1004") {
    Message.error("登入过期,请重新登入");
    storage.rm("token");
    location.reload();
  }
  return config; //就是放行
});

export default http;
